#include <stdio.h>
#include <stdbool.h>
void pcap_file_read(char *filePath);
int main(int argc, char *const argv[])
{
    char *filePath = argv[1];
    pcap_file_read(filePath);
    return 0;
}
void pcap_file_read(char *filePath)
{
    unsigned char pcap_file_header[24] = {0}; /*file header 24 bytes*/
    unsigned char pkt_hdr[16] = {0};          /*pkt_hdr 16 bytes*/
    unsigned char udp_pkt_data[4096] = {0};   /*content*/
    int len = 0;
    int pkt_cnt = 0;
    bool isLittleEndian = false; /*big endian*/

    FILE *pInFile = fopen(filePath, "rb"); /*open pcap file*/
    if (NULL == pInFile)
    {
        return;
    }
    if (1 != fread(pcap_file_header, 24, 1, pInFile)) /*read pcap file header*/
    {
        fclose(pInFile);
    }
    /*交换顺序读取*/
    if ((0xD4 == pcap_file_header[0]) && (0xC3 == pcap_file_header[1]) && (0xB2 == pcap_file_header[2]) && (0xA1 == pcap_file_header[3]))
    {
        isLittleEndian = true;
    }
    if (isLittleEndian)

        while (1)
        {
            if (1 != fread(pkt_hdr, 16, 1, pInFile)) /*read a pkt_hdr 16 bytes*/
            {
                break;
            }

            if (isLittleEndian) /*get the pktcontent's length in the file following the pkt_hdr*/
            {
                len = ((pkt_hdr[11]) << 24) + ((pkt_hdr[10]) << 16) + ((pkt_hdr[9]) << 8) + (pkt_hdr[8]);
            }
            else
            {
                len = ((pkt_hdr[8]) << 24) + ((pkt_hdr[9]) << 16) + ((pkt_hdr[10]) << 8) + (pkt_hdr[11]);
            }
            /*read the length bytes from file, this is the pktcontent*/
            if (1 != fread(udp_pkt_data, len, 1, pInFile))
            {

                break;
            }
            pkt_cnt++;
            printf("第%i个包的数据:", pkt_cnt);

            char ip[100];
            sprintf(ip, "%i.%i.%i.%i   ", udp_pkt_data[26], udp_pkt_data[27], udp_pkt_data[28], udp_pkt_data[29]);
            printf("ip == %s ", ip);
            printf("ip16进制数据 == %02x %02x %02x %02x", udp_pkt_data[26], udp_pkt_data[27], udp_pkt_data[28], udp_pkt_data[29]);

            printf("\n");
        }
    printf("Total %d packets found\n", pkt_cnt);
    fclose(pInFile);
}